package com.week.tiny_video.controller;

import com.week.tiny_video.core.MySessionContext;
import com.week.tiny_video.pojo.User;
import com.week.tiny_video.pojo.Video;
import com.week.tiny_video.pojo.sessionId;
import com.week.tiny_video.result.Result;
import com.week.tiny_video.service.CategoryService;
import com.week.tiny_video.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@CrossOrigin(allowCredentials = "true")
@RestController
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private CategoryService categoryService;
    private static String FILE_ADDRESS = "D:\\video";


    //查看我发布的视频 。
    // status为审核状态，0：待审核  1：已审核通过
    @GetMapping("videos/{status}")
    public Result listByUserAndStatus(@PathVariable("status") Integer status,
                                      HttpSession session){
        User user = (User) session.getAttribute("user");
        HashMap<String,Object> map = new HashMap<>();
        if(null != user){
            List<Video> list = videoService.listByUserAndStatus(user.getId(),status);
            map.put("list",list);
            return new Result(200,"视频",true,map);
        }
        return new Result(400,"失败",false);

    };

    //管理员查看所有待审核的视频
    @GetMapping("videos/status/{status}")
    public Result listByStatus(@PathVariable("status") Integer status){
        List<Video> list = videoService.listByStatus(status);
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",list);
        return new Result(200,"待审核列表",true,map);

    }

    //查找不同分类下的视频
    @GetMapping("videos/category/{category}")
    public Result listByCategory(@PathVariable("category") Integer cid){
        List<Video> list = videoService.findListByCategory(cid);
        HashMap<String,Object> map = new HashMap<>();
        map.put("list",list);
        return new Result(200,"视频分类列表",true,map);
    }

    //根据视频id查看视频详情
    @GetMapping("video/{id}")
    public Result get(@PathVariable("id") Integer id){
        Video video = videoService.get(id);
        HashMap<String,Object> map = new HashMap<>();
        map.put("video",video);
        return new Result(200,"视频详情",true,map);
    }


    //上传视频

    @PostMapping("video/upload")
    public Result upload(@RequestParam("file")MultipartFile file)
            throws IllegalStateException, IOException {

        sessionId instance = sessionId.getInstance();
        String id = instance.getId();
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(id);
        System.out.println(session.getId());
        System.out.println("上传开始");
        Video video = new Video();
        video.setName("测试");
        User user = (User) session.getAttribute("user");
        if(null == user){
            System.out.println("111111111111111");
        }
        video.setUser(user);
        video.setStatus(0);
        video.setUploadTime(new Date());
        video.setCategory(categoryService.get(1));
        if(!file.isEmpty()){
            String  path = FILE_ADDRESS;
            //如果父文件夹不存在 则创建文件夹 文件夹为path,视频名字file.getOriginalFilename()
            File filepath = new File(path,file.getOriginalFilename());
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            File fi = new File(path + File.separator + file.getOriginalFilename());
            //下载到本地
            file.transferTo(fi);

            String localAddress = fi.getCanonicalPath();
            System.out.println("getCanonicalPath"+localAddress);
            System.out.println("getAbsolutePath:"+fi.getAbsolutePath());
            video.setUrl(localAddress);
            video.setThumbnailUrl("测试");
//            //后缀名
////            String suffix = localAddress.substring(localAddress.lastIndexOf("."), localAddress.length());
//            System.out.println(localAddress.ge);
            videoService.add(video);
            HashMap<String,Object> map = new HashMap<>();
            map.put("url",localAddress);
            return new Result(200,"上传成功",true,map);

        }

        return new Result(400,"上传失败",false);

    }

    @PostMapping("video")
    public Result video(@RequestBody Video video){
        sessionId instance = sessionId.getInstance();
        String id = instance.getId();
        MySessionContext myc= MySessionContext.getInstance();
        HttpSession session = myc.getSession(id);
        User user = (User) session.getAttribute("user");
        if(user != null){
            video.setUser(user);
        }
        video.setStatus(0);
        video.setUploadTime(new Date());

        videoService.add(video);
        return new Result(200,"上传成功",true);
    }


}
